<!--
 * @Description: 医院管理
 * @Date: 2023-07-27 14:37:42
 * @FilePath: \hk-marketing-crm\src\views\system\hospital\index.vue
-->
<template>
	<div class="box-container layout-padding">
		<el-card class="left" ref="contentContainer" v-loading="state.treeLoading" element-loading-text="数据加载中...">
			<template #header>
				<div class="card-header">
					<span>医院信息维护</span>
					<!-- <el-button class="button">button</el-button> -->
				</div>
			</template>
			<div class="content" :style="{ height: height - 50 + 'px' }">
				<el-tree node-key="id" :data="state.treeData" :props="defaultProps" current-node-key="1" highlight-current @node-click="handleNodeClick">
					<template #default="scope">
						<span class="el-tree-node__label">
							<slot :row="scope">
								{{ scope.node.label }}
							</slot>
						</span>
					</template>
				</el-tree>
			</div>
		</el-card>

		<el-card shadow="hover" class="layout-padding-auto">
			<div class="box-search mb15">
				<el-input v-model="state.keyword" size="default" placeholder="请输入医院名称（模糊搜索）" style="max-width: 300px" clearable> </el-input>
				<el-button size="default" type="primary" class="ml10" @click="onHandleSearch">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAdd('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增医院
				</el-button>
			</div>

			<el-table
				:data="state.tableData.data"
				v-loading="state.tableData.loading"
				style="width: 100%"
				row-key="id"
				default-expand-all
				:tree-props="{ children: 'children' }"
			>
				<el-table-column prop="area" label="医院所在区域" show-overflow-tooltip> </el-table-column>
				<el-table-column prop="name" label="医院名称" show-overflow-tooltip> </el-table-column>
				<!-- <el-table-column prop="alias" label="医院别名" show-overflow-tooltip width="250"> </el-table-column> -->
				<el-table-column prop="levelName" label="医院等级"> </el-table-column>
				<!-- <el-table-column label="排序" show-overflow-tooltip width="80">
					<template #default="scope">
						{{ scope.$index }}
					</template>
				</el-table-column> -->
				<!-- <el-table-column prop="status" label="部门状态" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.status">启用</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
				</el-table-column> -->
				<!-- <el-table-column prop="remark" label="备注" show-overflow-tooltip width="250"></el-table-column> -->
				<el-table-column label="操作" show-overflow-tooltip width="140" fixed="right">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEdit('edit', scope.row)">编辑</el-button>
						<el-button size="small" text type="primary" @click="onTabelRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 50]"
				v-model:current-page="state.tableData.param.pageNum"
				v-model:page-size="state.tableData.param.pageSize"
				background
				layout="total, sizes, prev, pager, next"
				:total="state.tableData.total"
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
			>
			</el-pagination>
		</el-card>
		<HospitalDialog ref="dialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemHospital">
import { defineAsyncComponent, ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useHospitalApi } from '/@/api/system/hospital';
import { useElementSize } from '@vueuse/core';

const contentContainer: any = ref(null);
const { height } = useElementSize(contentContainer);

const defaultProps = {
	children: 'children',
	label: 'regionName',
};

// 引入组件
const HospitalDialog = defineAsyncComponent(() => import('/@/views/system/hospital/hospitalDialog.vue'));

// 定义变量内容
const dialogRef = ref();
const state = reactive<any>({
	treeLoading: false,
	treeData: [], //树形数据

	keyword: '', //搜索关键字
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
		},
	},
});

// 页面加载时
onMounted(async () => {
	await queryTree();
	await getTableData();
});

const onHandleSearch = () => {
	getTableData({
		cityIds: '',
		name: state.keyword,
		...state.tableData.param,
	});
};

const queryTree = async () => {
	state.treeLoading = true;
	const { data } = await useHospitalApi().queryCityTree();
	state.treeLoading = false;
	addNumToTree(data);
	let China = {
		id: '1',
		regionCode: '100000',
		regionId: '-1',
		regionLevel: 0,
		regionName: '全国',
		regionParentId: '0',
	};
	state.treeData = [China, ...data];
};

const addNumToTree = (tree: any) => {
	if (!tree || !Array.isArray(tree)) {
		return;
	}

	for (let i = 0; i < tree.length; i++) {
		const item = tree[i];
		if (item.hospitals && item.hospitals.length > 0) {
			item.num = item.hospitals.length;
			item.regionName = item.regionName + ' (' + item.num + ')';
		} else {
			item.num = 0;
		}
		if (item.children && item.children.length > 0) {
			addNumToTree(item.children);
		}
	}
};

const handleNodeClick = (data: any) => {
	if (data.regionName === '全国') {
		getTableData({
			cityIds: '',
			name: '',
			...state.tableData.param,
		});
	} else {
		getTableData({
			cityIds: data.id,
			name: '',
			...state.tableData.param,
		});
	}
};

// 初始化表格数据
const getTableData = async (
	params: { cityIds: string; name: string; pageNum: number; pageSize: number } = {
		cityIds: '',
		name: '',
		pageNum: 1,
		pageSize: 10,
	}
) => {
	state.tableData.loading = true;
	state.tableData.data = [];

	const { data } = await useHospitalApi().queryHospitalListByPaging(params);
	state.tableData.loading = false;
	state.tableData.data = data.records.map((item: any) => {
		return {
			...item,
			area: item.provinceName + ' / ' + item.cityName + (item.districtName ? ' / ' + item.districtName : ''),
		};
	});
	state.tableData.total = data.total;

	setTimeout(() => {
		state.tableData.loading = false;
	}, 3000);
};

// 打开新增菜单弹窗
const onOpenAdd = (type: string) => {
	dialogRef.value.openDialog(type);
};

// 打开编辑菜单弹窗
const onOpenEdit = (type: string, row: any) => {
	dialogRef.value.openDialog(type, row);
};

// 删除当前行
const onTabelRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除：${row.name}, 是否继续?`, '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			const res = await useHospitalApi().delHospital({ id: row.id });
			if (res.code === 200) {
				getTableData();
				ElMessage.success('删除成功');
			}
		})
		.catch(() => {});
};

// 分页大小改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData({
		cityIds: '',
		name: '',
		...state.tableData.param,
	});
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData({
		cityIds: '',
		name: '',
		...state.tableData.param,
	});
};
</script>

<style lang="scss" scoped>
.box-container {
	display: flex;
	flex-direction: row;
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}

	.left {
		height: 100%;
		width: 16%;

		:deep(.el-card__body) {
			padding: 0;
		}
		.card-header {
			font-size: 22px;
		}
		.content {
			height: 500px;
			padding: 10px;
			overflow-y: scroll;

			:deep(.el-tree) {
				.el-tree-node__content {
					height: 30px;
				}
				// .el-tree-node:focus > .el-tree-node__content {
				// 	background: #009688;
				// 	color: #fff;
				// }
			}
		}
	}
}
</style>
